package com.example.reagent_management.ui.operatedialog.repository

import androidx.lifecycle.asFlow
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.reagent_management.room.dao.StoreDao
import com.example.reagent_management.room.entity.GetAllCounts
import com.example.reagent_management.room.entity.InStoreChoose
import com.example.reagent_management.room.entity.OperateInfoQuery
import com.example.reagent_management.room.entity.ReagentOperate
import com.example.reagent_management.ui.activity.pojo.RemindDateAndCount
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flowOf

import javax.inject.Inject
import javax.inject.Singleton

//出入库唯一数据源
@Singleton
class StoreRepository @Inject constructor(private val storeDao: StoreDao) {
    fun insertOperate(reagentOperate: ReagentOperate): Long {
        return storeDao.insertReagent(reagentOperate)
    }

    /*
    * 批号+试剂id 总数量 统计在入库里
    * */
    fun getLastCounts(batch: String, reagent_id: Long): GetAllCounts? {
        return storeDao.getInStoreCounts(batch, reagent_id, 1) ?: return null
    }

    fun getBatchList(reagent_id: Long): Flow<PagingData<InStoreChoose>> {
        return Pager(
            config = PagingConfig(
                pageSize = 20,
                maxSize = 100,
                enablePlaceholders = false
            ), pagingSourceFactory = { storeDao.getBatchList(reagent_id) }).flow
    }

    fun updateInStore(counts:Long , storeId : Long):Int{
        return storeDao.updateCounts(counts,storeId)
    }

    /*
    * 根据id 获取 到供应商和数量
    * */
    fun getSupplierAndNum(id : Long):OperateInfoQuery{
        return storeDao.getSupplierAndNum(id)
    }

    fun getOperateInfo(id: Long):ReagentOperate?{
        return storeDao.getOperate(id)
    }

    fun deleteById(id: Long):Int {
        return storeDao.deleteOperateById(id)
    }

    /*
    * 更新总数
    * */
    fun updateLastCounts(id: Long,counts: Long):Int{
        return storeDao.updateLastCounts(id,counts)
    }

    fun getNumById(id: Long):Long{
        return storeDao.getNumById(id)?:return 0L
    }

    /*
    * 获取counts字段 主要出库来获取关联入库的id
    * */
    fun getCountsById(id: Long):Long{
        return storeDao.getCounts(id)
    }

    /**
     * 获取提醒信息
     */
    fun getRemindInfo(): Flow<List<RemindDateAndCount>> {
        return storeDao.remindInfo.asFlow()
    }

    /**
     * 清理
     */
    fun cleanStore(){
        storeDao.cleanInStore()
        storeDao.cleanOutStore()
    }

}